package com.abe.signaturesdk;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;


import com.abe.signaturesdk.views.SignaturePad;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import static com.abe.signaturesdk.CommonTool.Dp2Px;

public class ElectronicSignatureDialog extends Dialog {
    private String SD_PATH = Environment.getExternalStorageDirectory().getPath();
    private String ELECTRONIC_SIGNATURE_PATH = SD_PATH + File.separator + "Signature";
    private Context mContext;
    private SignaturePad mSignaturePad;
    private Button mClearButton;
    private Button mSaveButton;
    private Button negativeButton;
    private ImageView et_riqi;
    private String imgName = "";
    private ElectronicSignatureCallBackListener mCallBackListener;
    private Boolean qmhp = false;
    private int SCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    private Activity activity;

    public ElectronicSignatureDialog(Context context) {
        super(context);
        this.mContext = context;
        if (context instanceof Activity) {
            activity = (Activity) context;
        }
        setOwnerActivity(activity);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    public ElectronicSignatureDialog(Context context, ImageView et_riqi) {
        this(context);
        this.et_riqi = et_riqi;
    }

    public ElectronicSignatureDialog(Context context, String imgName) {
        this(context);
        this.imgName = imgName;
    }

    public ElectronicSignatureDialog(Context context, ImageView et_riqi,
                                     String imgName) {
        this(context, et_riqi);
        this.imgName = imgName;
    }

    public void setCallBackListener(
            ElectronicSignatureCallBackListener mCallBackListener) {
        this.mCallBackListener = mCallBackListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.electronic_signature);
        init();
    }

    private void init() {
        initView();
        initEvent();
    }

    private void initView() {
        mSignaturePad = (SignaturePad) findViewById(R.id.signature_pad);
        mClearButton = (Button) findViewById(R.id.clear_btn);
        mSaveButton = (Button) findViewById(R.id.positiveButton);
        negativeButton = (Button) findViewById(R.id.negativeButton);
    }

    private void initEvent() {
        mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
            @Override
            public void onStartSigning() {
            }

            @Override
            public void onSigned() {
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
            }

            @Override
            public void onClear() {
                mSaveButton.setEnabled(false);
                mClearButton.setEnabled(false);
            }
        });

        mClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSignaturePad.clear();
            }
        });

        mSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                if (addJpgSignatureToGallery(signatureBitmap, imgName)) {
                    if (mCallBackListener != null) {
                        mCallBackListener.callBack();
                    }
                }
                if (qmhp) {
                    if (SCREEN_ORIENTATION != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                        activity.setRequestedOrientation(SCREEN_ORIENTATION);
                    }
                }
                dismiss();
            }
        });
        negativeButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (qmhp) {
                    if (SCREEN_ORIENTATION != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                        activity.setRequestedOrientation(SCREEN_ORIENTATION);
                    }
                }
                dismiss();
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (mCallBackListener != null) {
            mCallBackListener.cancel();
        }
    }

    public File getAlbumStorageDir(String albumName) {
        File file = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created");
        }
        return file;
    }

    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        stream.close();
    }

    public void saveBitmapToPNG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.argb(0, 0, 0, 0));
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        stream.close();
    }

    public boolean addJpgSignatureToGallery(Bitmap signature, String name) {
        boolean result = false;
        try {
            if (name != null && !name.equals("")) {
                File photo = new File(ELECTRONIC_SIGNATURE_PATH, name
                        + ".png");
                File dir = new File(ELECTRONIC_SIGNATURE_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                setImageView(et_riqi, signature);
                saveBitmapToPNG(signature, photo);
                scanMediaFile(photo);
            } else {
                setImageView(et_riqi, signature);
            }
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void scanMediaFile(File photo) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(photo);
        mediaScanIntent.setData(contentUri);
        mContext.sendBroadcast(mediaScanIntent);
    }

    public boolean addSvgSignatureToGallery(String signatureSvg) {
        boolean result = false;
        try {
            File svgFile = new File(getAlbumStorageDir("SignaturePad"),
                    String.format("Signature_%d.svg",
                            System.currentTimeMillis()));
            OutputStream stream = new FileOutputStream(svgFile);
            OutputStreamWriter writer = new OutputStreamWriter(stream);
            writer.write(signatureSvg);
            writer.close();
            stream.flush();
            stream.close();
            scanMediaFile(svgFile);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void setImageView(ImageView img, Bitmap bitmap) {
        if (img != null)
            img.setImageBitmap(bitmap);
    }

    public void setDialogWindowAttr() {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = LayoutParams.MATCH_PARENT;// 宽高可设置具体大小
        lp.height = 1000;
        getWindow().setAttributes(lp);
    }

    public void setDialogWindowAttr(Context context, Boolean qmhp) {
        this.qmhp = qmhp;
        if (qmhp) {
            SCREEN_ORIENTATION = activity.getRequestedOrientation();
            // 设置打开签名固定横屏模式
            if (SCREEN_ORIENTATION != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = LayoutParams.MATCH_PARENT;// 宽高可设置具体大小
        if (qmhp) {
            lp.width = LayoutParams.MATCH_PARENT;
        } else {
            WindowManager wm = (WindowManager) getContext()
                    .getSystemService(Context.WINDOW_SERVICE);
            int height = wm.getDefaultDisplay().getHeight();
            if (height < Dp2Px(context, 500)) {
                lp.height = LayoutParams.MATCH_PARENT;
            } else {
                lp.height = Dp2Px(context, 500);
            }
        }
        getWindow().setAttributes(lp);
    }
}